package com.kkang.ch2.el;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;

/**
 * 配置类
 *
 * @author yongk_liu
 **/
@Configuration
@ComponentScan("com.kkang.ch2.el")
@PropertySource("classpath:com/kkang/ch2/el/test.properties")//配置文件地址后，可使用@value获取
public class ElConfig {

    @Value("正常value直接写入")//普通直接注入
    private String normal;

    @Value("#{systemProperties['os.name']}")//操作系统信息
    private String osName;

    @Value("#{T(java.lang.Math).random() * 100.0}")//表达式结果
    private double randomNumber;

    @Value("#{demoService.author}")//其他类/bean的属性
    private String fromAnother;

    @Value("classpath:com/kkang/ch2/el/zz-readme.txt")//文件资源
    private Resource testFile;

    @Value("http://baidu.com")//网页资源
    private Resource testUrl;

    @Value("${book.name}")//直接使用PropertySource解析的文件内容
    private String bookName;

    @Autowired
    private Environment environment;//可以从这个bean获取Properties

    @Bean//使用PropertySource 并使用@Value 获取，使用必须配置这个bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    public void outputResource() {
        try {
            System.out.println(normal);
            System.out.println(osName);
            System.out.println(randomNumber);
            System.out.println(fromAnother);
            System.out.println(IOUtils.toString(testFile.getInputStream(), "utf-8"));
            System.out.println(IOUtils.toString(testUrl.getInputStream(), "utf-8"));
            System.out.println(environment.getProperty("book.name"));//可以直接从envirment中获取propertiesSource中读取的配置文件
        } catch (Exception e) {

        }

    }

}
